package com.easy.lab.shixun.controller.ws;

import com.easy.lab.shixun.api.service.GroupMemberService;
import com.easy.lab.shixun.common.base.BaseException;
import com.easy.lab.shixun.common.constant.RequestConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;


/**
 * ws握手处理器
 * 返回ws用的身份令牌（直接使用用户令牌token）
 * @Author: https://gitee.com/wesleyOne
 * @Date: 12.07 2019
 */
@Component
@Slf4j
public class SimplePrincipalHandshakeHandler extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {

        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
            HttpServletRequest httpRequest = servletServerHttpRequest.getServletRequest();
            // 从请求参数中获取token并作为s身份令牌
            String token =  httpRequest.getParameter(RequestConstant.TOKEN);
            if (StringUtils.isNotBlank(token)) {
                return () -> token;
            }
        }
        return null;
    }

}
